from fastapi import Request
from fastapi.responses import RedirectResponse
from nicegui import Client, app
from starlette.middleware.base import BaseHTTPMiddleware
from settings import unrestricted_page_routes


# 2.认证中间件（这部分改的官方样例），用来判断登录状态，及未认证情况下的操作
class AuthMiddleware(BaseHTTPMiddleware):

    async def dispatch(self, request: Request, call_next):
        # 3.判断是否登录
        if not app.storage.user.get("authenticated", False):
            # 4.如果未登录，并且页面需要登录后可见，就重定向到login页面
            if (
                request.url.path in Client.page_routes.values()
                and request.url.path not in unrestricted_page_routes
            ):
                app.storage.user["referrer_path"] = request.url.path
                return RedirectResponse("/login")
        return await call_next(request)
